package com.hmjk.health.health;





import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.hmjk.health.R;
import com.hmjk.health.views.MutilModeImageTextView;




import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class HealthCardBloodSugarAlarmGridActivity extends Activity{


    private Spinner spinner2;
 //   private ArrayAdapter adapter2;
	
	private GridView mGridView;
	private GridViewAdapter mAdapter1;
    private GridView grid;  
    private BloodSugarAlarm mBloodSugarAlarm = new BloodSugarAlarm();
    final int MAX_BUTTONS = 81;
	int [][] curplan =new  int[BloodSugarAlarm.MAXDAY][BloodSugarAlarm.MAXDETECTION];  //当前计划
   
    private String []  titlestr={"凌晨","空腹","早餐后","午餐前","午餐后","晚餐前","晚餐后","睡前","星期"};

    private String []  datestr={"  ","周日","周一","周二","周三","周四","周五","周六"};

    private String []  reminderstr={"03:00","06:10","7:30","11:30","13:00","17:50","18:30","22:00"};
    
	private String [] mSimpleUnitOfG;
	private int year, monthOfYear, dayOfMonth, hourOfDay, minute;

	private int[] buttonstate = new int [MAX_BUTTONS];
	
	private int  cellHeight =72;
	private int  cellFontSize =18;
	private int  cellFontmidSize =14;
	private int  cellFontnormalSize =16;
	private int  cellFontminiSize =12;
	
	private int  dayremind[] =
		{
			/*  竖向   */		
            10, 19, 28, 37, 46, 55, 64, 73,
            11, 20, 29, 38, 47, 56, 65, 74,
            12, 21, 30, 39, 48, 57, 66, 75,
            13, 22, 31, 40, 49, 58, 67, 76,
            14, 23, 32, 41, 50, 59, 68, 77,
            15, 24, 33, 42, 51, 60, 69, 78,
            16, 25, 34, 43, 52, 61, 70, 79
            
  /*    横向      
            10,   11,   12,   13,   14,   15,   16,   17, 
            19,   20,   21,   22,   23,   24,   25,   26, 
            28,   29,   30,   31,   32,   33,   34,   35, 
            37,   38,   39,   40,   41,   42,   43,   44, 
            46,   47,   48,   49,   50,   51,   52,   53, 
            55,   56,   57,   58,   59,   60,   61,   62, 
            64,   65,   66,   67,   68,   69,   70,   71 	
 */           		
	    };
	
	
//	private String [] mSimpleUnitOfMl;
//	private int mBasicRadioUnit = 1;
	List<Integer> mCheckedList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.healthcard_bloodsugar_guage_reminder);
		initdate();
  //      adapter2 = ArrayAdapter.createFromResource(this, R.array.plantes, android.R.layout.simple_spinner_item);
        
        //ʨ׃Ђ-±?·繱 
// adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        //½«adapter2 ͭ¼ӵ½spinnerא
  //      spinner2.setAdapter(adapter2);
		
		TextView t3 = (TextView) findViewById(R.id.health_card_reminder_link); 
//		t3.setText(Html.fromHtml( "<b>text3:</b> Text with a " 
//		+ "<a href="http://www.google.com">link</a> " +"created in the Java source code using HTML.")); 
//		String html ="<a href='http://www.baidu.com'>帮助>></a>";
//		CharSequence charSequence = Html.fromHtml(html);
//		t3.setText(charSequence);
//		t3.setMovementMethod(LinkMovementMethod.getInstance());		
		t3.setText(Html.fromHtml("<a href=\"http://www.baidu.com/CAIYUNFREEDOM\">帮助>></a>"));		
			
		initspinnerview();
		
		initView(this);
	}
    void initspinnerview ()
	{
    	// 初始化控件
    	 spinner2 = (Spinner) findViewById(R.id.Spinner01);
    	// 建立数据源
    	String[] mItems = getResources().getStringArray(R.array.bloodtestplans);
    	// 建立Adapter并且绑定数据源
    	ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mItems);
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	//绑定 Adapter到控件
    	spinner2 .setAdapter(adapter);
//    	spinner.setSelection(1);
    	spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
    	   // @Override
    	    public void onItemSelected(AdapterView<?> parent, View view, 
    	            int pos, long id) {
    	    
 //   	        String[] languages = getResources().getStringArray(R.array.bloodtestplans);
 //   	        Toast.makeText(MyGridActivity.this, "你点击的是:"+languages[pos], 2000).show();
    	    	setalarmdate(pos);
    	    	HealthCardBloodSugarAlarmGridActivity.this.mAdapter1.notifyDataSetChanged();
    	    }
    	    //@Override
    	    public void onNothingSelected(AdapterView<?> parent) {
    	        // Another interface callback
    	    	  Toast.makeText(HealthCardBloodSugarAlarmGridActivity.this, "你没选", 500).show();
    	    }
    	});
		
	}
	
    //OnItemSelected监听器  
    private class  ProvOnItemSelectedListener implements OnItemSelectedListener{          
        @Override  
        public void onItemSelected(AdapterView<?> adapter,View view,int position,long id) {  
            //获取选择的项的值  
            String sInfo=adapter.getItemAtPosition(position).toString();  
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();             
        }  
  
        @Override  
        public void onNothingSelected(AdapterView<?> arg0) {  
            String sInfo="什么也没选！";  
            Toast.makeText(getApplicationContext(),sInfo, Toast.LENGTH_LONG).show();  
              
        }  
    }      
    
    public void initdate()
    {
    	for(int i=0;i<MAX_BUTTONS;i++)
    	{
    		buttonstate[i]=mBloodSugarAlarm.ALARM_NONE;
    	}
    	for(int i=0;i<56;i++)
    	{
    		buttonstate[dayremind[i]]=mBloodSugarAlarm.plan_asymptomatic[i/8][i%8];
    	}	
    }
	
    public int Getcurplan()
    {
    	for(int i=0;i<56;i++)
    	{
    		curplan[i/8][i%8] =	buttonstate[dayremind[i]];
    	}
    	return mBloodSugarAlarm.Get_plan(curplan);
    }    
    
    public void Setcurplan(int[][] curplan)
    {
    	for(int i=0;i<56;i++)
    	{
    		curplan[i/8][i%8] =	buttonstate[dayremind[i]];
    	}
   // 	return mBloodSugarAlarm.Get_plan(curplan);
    }
    
    public void setalarmdate(int plan)
    {
    	int[][] tmpplan =mBloodSugarAlarm.Getdatafromplan(plan);

    	for(int i=0;i<MAX_BUTTONS;i++)
    	{
    		buttonstate[i]=mBloodSugarAlarm.ALARM_NONE;
    	}
    	for(int i=0;i<56;i++)
    	{
    		buttonstate[dayremind[i]]=tmpplan[i/8][i%8];
    	}	
    }
    
	@SuppressLint("NewApi")
	private void initView(final Context mContext){
		
		
		String[] mUnitArr = getResources().getStringArray(R.array.default_unit_date);
		mSimpleUnitOfG = Arrays.copyOfRange(mUnitArr, 1,7);
//		mSimpleUnitOfMl = Arrays.copyOfRange(mUnitArr, 7, mUnitArr.length);	
		mGridView = (GridView) findViewById(R.id.simple_unit_view);
//		mAdapter = new MyGridViewAdapter(mContext, mSimpleUnitOfG);
		 mAdapter1 = new GridViewAdapter(this);
		mGridView.setAdapter(mAdapter1);
//		setGridViewHeightBaseOnChildren(mGridView);	
//		mGridView.setColumnWidth(columnWidth)
		
		
		mGridView.setOnItemClickListener(new OnItemClickListener()
        {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id)
                {
                   //     Log.i("MyGridActivity", "Position:" + position);
              	      MutilModeImageTextView vv;
              	      int realloc;
                      switch(position) 
                      {
                      case 0:
                        Log.i("MyGridActivity", buttonstate[position]+"XXXPosition:" + position);
                    	  buttonstate[position]=(buttonstate[position]-1+mBloodSugarAlarm.MAX_ALARM_STATE)%mBloodSugarAlarm.MAX_ALARM_STATE;
                          Log.i("MyGridActivity", buttonstate[position]+"XXXPosition:" + mBloodSugarAlarm.MAX_ALARM_STATE);

           //         	  for(int i=0;i<56;i++)
           //         	  {
           //         		  buttonstate[dayremind[i]]= buttonstate[position];
           //         		  vv=(MutilModeImageTextView) mGridView.getChildAt(dayremind[i]);
           //                   vv.updatebackground(buttonstate[dayremind[i]]);
           //         	  }
                                              	  
                    	  break;
                      case 9: case 18: case 27: case 36: case 45: case 54: case 63: case 72: //time
                   	  
 //                     case 1: case 2: case 3: case 4: case 5: case 6: case 7:   //plan
                    	  buttonstate[position]=(buttonstate[position]-1+mBloodSugarAlarm.MAX_ALARM_STATE)%mBloodSugarAlarm.MAX_ALARM_STATE;
                    	  int k=position/9-1;
                    	  for(int i=0;i<7;i++)
                    	  {
                    		  realloc =(k)+8*i;
                    		  buttonstate[dayremind[realloc]]= buttonstate[position];
                    		  vv=(MutilModeImageTextView) mGridView.getChildAt(dayremind[realloc]);
                              vv.updatebackground(buttonstate[dayremind[realloc]]);
                    	  }

                      break;
                      
 //                     case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80:
                      case 1: case 2: case 3: case 4: case 5: case 6: case 7:   //plan

                    	  buttonstate[position]=(buttonstate[position]-1+mBloodSugarAlarm.MAX_ALARM_STATE)%mBloodSugarAlarm.MAX_ALARM_STATE;
                    	  int m=position-1;
                    	  for(int i=0;i<8;i++)
                    	  {
                    		  realloc =m*8+i;
                    		  buttonstate[dayremind[realloc]]= buttonstate[position];
                    		  vv=(MutilModeImageTextView) mGridView.getChildAt(dayremind[realloc]);
                             vv.updatebackground(buttonstate[dayremind[realloc]]);
                   	  }	  
                      break;

                      case 10: case 11: case 12: case 13: case 14: case 15: case 16:  
                      case 19: case 20: case 21: case 22: case 23: case 24: case 25:  
                      case 28: case 29: case 30: case 31: case 32: case 33: case 34:  
                      case 37: case 38: case 39: case 40: case 41: case 42: case 43:  
                      case 46: case 47: case 48: case 49: case 50: case 51: case 52:  
                      case 55: case 56: case 57: case 58: case 59: case 60: case 61:  
                      case 64: case 65: case 66: case 67: case 68: case 69: case 70:  
                      case 73: case 74: case 75: case 76: case 77: case 78: case 79:  
                    	                     	  buttonstate[position]=(buttonstate[position]-1+mBloodSugarAlarm.MAX_ALARM_STATE)%mBloodSugarAlarm.MAX_ALARM_STATE;
                    	  Log.e("XXXXXXX263", buttonstate[position]+"Position:" + position);
                    	  break;
                      
                      
                      
             //           case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80:
       	  
                      //case 9: case 18: case 27: case 36: case 45: case 54: case 63:  //day
                      case 17: case 26: case 35: case 44: case 53: case 62: case 71: case 80: 	   
                    	  final TextView tmptext = ( TextView)(v); 
                    	  String str_hourminute =(String)tmptext.getText();
                    	  if(5==str_hourminute.length())
                    	  {	  
                    	     hourOfDay = getHour(str_hourminute,':');
                    	     minute = getMinute(str_hourminute,':');
                    	  }
                    	  
                          TimePickerDialog timePickerDialog = new TimePickerDialog(HealthCardBloodSugarAlarmGridActivity.this, new TimePickerDialog.OnTimeSetListener()
                             {
                                @Override
                                public void onTimeSet(TimePicker view, int hourOfDay, int minute)
                                {
                            	  tmptext.setText(hour_minute_tostr(hourOfDay, minute));
                                }
                             }, hourOfDay, minute, true);
                          
                          timePickerDialog.show();

                      break;	  
                      
  
                      }
                      
                   //   int icurplan= Getcurplan();
                   //   if(icurplan!=0)
                      Setcurplan(mBloodSugarAlarm.cur_plan);
                	  spinner2.setSelection(Getcurplan());

                }
        });


		
    }
    
	String intadd0formattostr(int i,int max0)
	{
		String strtmp;
		int len=0;
		strtmp="00000000"+Integer.toString(i);
		if(max0>7)
		{
			len=7;	
		}
		else
		{
			len =max0;
		}
		strtmp=strtmp.substring(strtmp.length()-max0, strtmp.length());
		return strtmp;
		
	}
	
	
	
    String hour_minute_tostr(int hour,int min)
    {   
    	String strh,strm;
    	strh=intadd0formattostr(hour,2);
    	strm=intadd0formattostr(min,2);
   	    return strh+":"+strm;
    }	
    
    int getHour(String str,char splitc)
    {     int h;
     	  String str_hour = str.substring(0, str.indexOf(splitc));
     	  h =Integer.parseInt(str_hour);
     	  return h;
    }
    
    int getMinute(String str,char splitc)
    {     int min;
     	  String str_min = str.substring(str.indexOf(splitc)+1,str.length());
     	  min =Integer.parseInt(str_min);
     	  return min;
    }
	


    private class GridViewAdapter extends BaseAdapter {  
        
        private Context context;  
          
        public GridViewAdapter(Context context) {  
            this.context = context;  
        }  
          
        int count = MAX_BUTTONS;  
  
        @Override  
        public int getCount() {  
            return count;  
        }  
  
        @Override  
        public Object getItem(int position) {  
            return position;  
        }  
  
        @Override  
        public long getItemId(int position) {  
            return position;  
        }  
  
        private void updateItem(int index)
        {
//        	MutilModeImageTextView view =   .getChildAt(index - visiblePosition);
//            TextView txt = (TextView) view.findViewById(R.id.textView1);
            // 获取mDataList.set(ids, item);更新的数据
//            MyListItem data = (MyListItem) getItem(index);
            // 重新设置界面显示数据
//            txt.setText(data.getData());
        }        
        
        
        
        @SuppressLint("NewApi")
		@Override  
        public View getView(int position, View convertView, ViewGroup parent) {  
  //          TextView resulttext = new TextView(context);  
        	//R.drawable.health_gluc_waterdrop      
        	MutilModeImageTextView result =new MutilModeImageTextView(context,R.drawable.health_gluc_none,R.drawable.health_gluc_waterdrop,
            		                         R.drawable.health_reminder_textview_bg,buttonstate[position]);
            if((0==position))
            {
            	//result.setTextSize(10);
            	result.setText(datestr[position]);
     //       	resulttext.setBackgroundColor(Color.GRAY); 
     //       	resulttext.setTextColor(Color.BLACK);  
            	result.setTextSize(cellFontmidSize);  
            	result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));  
            	result.setGravity(Gravity.CENTER);
             	result.setHeight(cellHeight);
            	
            }
            else         	
            if((position<8)&&(position>=1))
            {
            	//result.setTextSize(10);
            	result.setText(datestr[position]);
     //       	resulttext.setBackgroundColor(Color.GRAY); 
     //       	resulttext.setTextColor(Color.BLACK);  
            	result.setTextSize(cellFontmidSize);  
            	result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));  
            	result.setGravity(Gravity.CENTER);
         	    result.setBackgroundResource(result.mBTN_ResID_Background);
            	result.setHeight(cellHeight);
            	
            }
            else if((0==position%9)&&(position<=72)&&(position>0))
            {   
            	//result.setTextSize(10);
            	result.setText(titlestr[position/9-1]);
     //       	result.setBackgroundColor(Color.GRAY); 
     //       	resulttext.setTextColor(Color.BLACK);  
            	result.setTextSize(cellFontminiSize );  
            	result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));  
            	result.setGravity(Gravity.CENTER);  
            	result.setHeight(cellHeight);
            }	
            else if((8==position))
            {
            	//result.setTextSize(6);  

//            	MutilModeImageTextView result1 =new MutilModeImageTextView(context,R.drawable.health_time_icon,
//                        R.drawable.health_reminder_textview_bg);
//            	result1.setHeight(cellHeight); 
            	
//            	result1.setBackgroundResource(R.drawable.health_time_icon);
//            	result1.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));  
 //           	result1.setGravity(Gravity.CENTER);
             	
             	result.SetOnlyOneIagme(R.drawable.health_time_icon,R.drawable.health_reminder_mutiltextview_yellow_bg);
            	result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));  
            	result.setGravity(Gravity.CENTER);
            	result.setHeight(cellHeight); 

            }
            else if((0==(position+1)%9)&&(9<position))
            {
            	result.setTextSize(cellFontmidSize);
            	result.setText(reminderstr[(position+1)/9-2]);
            	result.setHeight(cellHeight);
         	    result.setBackgroundResource(result.mBTN_ResID_Background);
         	    
 //           	resulttext.setBackgroundColor(Color.GRAY); 
            }
            else
            {
          	   Log.e("XXXXXXX436", buttonstate[position]+"Position:" + position);

            	if(mBloodSugarAlarm.ALARM_ALLDAY==buttonstate[position])
            	{	
            	   result.setBackgroundResource(result.mBTN_ResID_Background);
            	   result.setHeight(cellHeight);
            	}
//            	else
//                if(mBloodSugarAlarm.ALARM_ONE==buttonstate[position])
//                {	
//                	result.setBackgroundResource(R.drawable.select_one_icon);
//                }
                else
                if(mBloodSugarAlarm.ALARM_NONE==buttonstate[position])
                 {	
                	    result.setHeight(cellHeight);
                    	result.setBackgroundResource(result.mBTN_ResID_Background);
                 }
//                    else	
//                {
//                	result.setBackgroundResource(R.drawable.select_three_icon);
//                }	
                result.setTextColor(Color.BLACK);  
//                result.setTextSize(cellFontSize);  

            }
            
            result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)));  
            result.setGravity(Gravity.CENTER);  
   
            //设置背景颜色  
            return result;  
        }  
          
    }  
	
	
	
}
